package com.tueye.web.controller.publishtopic;

import java.io.File;
import java.io.PrintWriter;
import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.tueye.ajax.json.JSONObject;
import com.tueye.cache.TuEyeCache;
import com.tueye.entity.Pictures;
import com.tueye.entity.Topics;
import com.tueye.entity.user.User;
import com.tueye.entity.user.UserCollectionInfo;
import com.tueye.service.ITopicService;
import com.tueye.utils.DateUtils;
import com.tueye.utils.FileHandle;
import com.tueye.utils.HtmlConverseUtil;
import com.tueye.utils.TuEyeConstant;
import com.tueye.utils.UUIDGenerator;
import com.tueye.utils.servlet.CaptchaServiceSingleton;



/**
 *  Title: UploadFileController.java
 *  Description: upload the imagess.
 * @author yuyue
 * @version 0.5 (for test)
 * 
 */
@SuppressWarnings("unchecked")
@Controller
public class UploadFileController {

	Log log = LogFactory.getLog(UploadFileController.class);
	
	@Autowired
	@Qualifier("topicService")
	ITopicService topicService;

	@Autowired
	@Qualifier("tueyecache")
	TuEyeCache tueyecache;
	
	
	/**
	 *  处理上传的文件
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/upload_image.do") 
    public String handleUploadProcess(HttpServletRequest request, HttpServletResponse response)   
            throws Exception {  
		PrintWriter out = response.getWriter(); 
		JSONObject obj = new JSONObject(); 
		obj.put("error", "dd");
		obj.put("data", "dee");
		User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
        if(user  == null){
        	 return "pages/topics/usermanager/userlogin";  
        }
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String fileid = request.getParameter("id");
		String topicid = request.getParameter("topicid");
//		System.out.println(fileid);
//		System.out.println(topicid+ "topicid");
		MultipartFile file  = multipartRequest.getFile("img"+fileid);
		String name = file.getOriginalFilename();
		
		//得到文件的后缀名   modify by yuyue 2009/5/7  下面注释一处是bug.因为有时候用户传的文件有多个.
	  //  String suffer = "."+name.split("\\.")[1];
	    String suffer = "."+name.substring(name.lastIndexOf(".")+1,name.length());
 		//String suffer = "jpg";
		String newpath = TuEyeConstant.PROJECTPATH+File.separatorChar+"temp"+File.separatorChar;
		String newName = topicid+"_"+fileid+suffer;
		//System.out.println("the file original name is  " + name);
		//System.out.println("the file new  name is  " + newName);
		file.transferTo(new File(newpath+newName));
	    out.print(obj.toString());
		 
        return null;   
    } 
	
	
	@RequestMapping("/imageform_process.do") 
    public String imagesFormProcess(HttpServletRequest request, Model model)   
            throws Exception {  
        String viewName = "pages/topics/publishtopic/publishsuccess"; 
        
        User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
        if(user  == null){
        	 return "pages/topics/usermanager/userlogin";  
        }
		 String topicid = request.getParameter("topicid");
		 if(topicid == null || "".equals(topicid) )
		 {
			 //这里要转到出错页面。
			 return "common/error";
		 }
		   String topic_code_page = request.getParameter("topic_code");
//		  boolean flag = CaptchaServiceSingleton.getInstance().validateCaptchaResponse(topic_code_page, request.getSession());
//		  if(flag == false){
//			  model.addAttribute("errcode", "<font color=red>验证码错误</font>");
//			  model.addAttribute("id", topicid); 
//			  return "pages/topics/publishtopic/uploadpictures";
//		  }
		 Topics topic = topicService.getTopicById(topicid);
         //图片新放的路经是项目/pages/topic/类型文件夹下/主题id/
		 String newPath = TuEyeConstant.PROJECTPATH+
		 				  File.separatorChar + topic.getTopic_type().getType_enlish_name()+
		 				  File.separatorChar + topic.getTopic_code()+ File.separatorChar ;
		 String oldPath = TuEyeConstant.PROJECTPATH + File.separatorChar+"temp"+File.separatorChar;
		 FileHandle filehander = new FileHandle();
		 filehander.cerateDirectory(newPath);
		 Integer mainPic = 10000;
		 if(request.getParameter("mainpic") != null) {
			mainPic = new Integer(request.getParameter("mainpic"));
		}
		 
          int i = 1;
          while(true){
        	  
        	  String pic_name = request.getParameter("imgname"+i);
        	  String pic_desc = request.getParameter("imgtext"+i);
        	   
        	  String pic_suffix = request.getParameter("imgsuffer"+i);
        	  if(pic_name == null && pic_desc == null){
        		  break;
        	  } else{
        		   pic_desc = HtmlConverseUtil.getInstance().encode(pic_desc);
        		   
        	  }
        	  Pictures picture = new Pictures();
        	  picture.setId(UUIDGenerator.getUUID());
        	  picture.setPicture_description(pic_desc);
        	  picture.setSys_time(DateUtils.getCurrentDate());
        	  picture.setTopics(topic);
        	  String newFilename = topicid + "_" + i + "." + pic_suffix ;
        	 // String pic_main = request.getParameter("imgname"+i);
        	  File oldFile = new File(oldPath+newFilename);
        	  File newFile = new File(newPath + newFilename);
        	  if(oldFile != null){
        	  oldFile.renameTo(newFile);
        	  picture.setPicture_url(newFilename);
        	  }
        	  if(i == mainPic){
        		  picture.setMain_picture(1);
        		  //CompressPicture mypic = new CompressPicture();
        		//  mypic.compressPic(newPath, newPath, newFilename, "show"+newFilename, 190, 140, true);
        	  }else{
        		  picture.setMain_picture(2);
        	  }
        	  picture.setPicture_name(pic_name);
        	  topicService.savePicture(picture);
        	  i++;
          }
          model.addAttribute("title", "<font color='red'>"+topic.getTopic_title()+"</font> 发布成功，TuEye管理员审核后便可显示出来");
        return viewName;   
    } 
	
	@RequestMapping("/publish.do") 
    public String toPublishTopic(HttpServletRequest request, Model model)   
            throws Exception {   
        //具体的业务逻辑操作。。。  
        User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
        if(user  == null){
        	 return "pages/topics/usermanager/userlogin";  
        }
		model.addAttribute("types", tueyecache.allTopicTypes()); 
        //return "pages/topics/publishtopic/publishtopic";   
        return "pages/article/publishtopic";   
    } 
	@RequestMapping("/publish_process.do") 
    public String publishProcess(HttpServletRequest request, Model model)   
            throws Exception {   
//          String viewName = "pages/topics/publishtopic/publishtopic"; 
          String viewName = "pages/article/publishtopic"; 
          
	          User user =  (User) request.getSession().getAttribute(TuEyeConstant.TUEYE_USER);
	          if(user  == null){
	          	 return "pages/topics/usermanager/userlogin";  
	          }
	          
            String topic_code_page = request.getParameter("topic_code");
            String topic_title =  HtmlConverseUtil.getInstance().encode(request.getParameter("topic_title"));
	 		String topic_overview = HtmlConverseUtil.getInstance().encode(request.getParameter("topic_overview"));
	 		String publi = HtmlConverseUtil.getInstance().encode(request.getParameter("publi"));
	 		String topic_type =  request.getParameter("topic_type");
	 		String topic_author = HtmlConverseUtil.getInstance().encode(request.getParameter("topic_author"));
	 		//modify by yuyue 09/5/23
	 		if(topic_author == null) {
				topic_author = user.getEmail();
			}
	 		String topic_from = HtmlConverseUtil.getInstance().encode(request.getParameter("topic_from"));
         boolean flag = CaptchaServiceSingleton.getInstance().validateCaptchaResponse(topic_code_page, request.getSession());
         if(flag == false){
        	 model.addAttribute("types", tueyecache.allTopicTypes());
        	 model.addAttribute("topic_title",topic_title );
        	 model.addAttribute("topic_overview", topic_overview);
        	 model.addAttribute("topic_author",topic_author );
        	 model.addAttribute("topic_from", topic_from); 
        	 model.addAttribute("errcode", "<font color=red>验证码错误</font>");
        	 return viewName;
         }
         Integer topicChange = 1;
         if(publi != null){
        	// topicChange = new Integer(publi);
         }
         
        Topics topic = new Topics();
        topic.setSys_time(DateUtils.getCurrentDate());
		topic.setTopic_author(topic_author);
		//topic.setTopic_change();
		//topic.setTopic_description(topic_overview);
		topic.setTopic_overview(topic_overview);
		topic.setTopic_title(topic_title);
		topic.setTopic_uploadDate(new Timestamp(System.currentTimeMillis()));
		topic.setTopic_release_type(0);
		topic.setTopic_change(topicChange);
		topic.setTopic_type(topicService.getTopicTypeById(topic_type));
		topic.setTopic_from(topic_from);
		//modify by yuyue add topic cod
		topic.setTopic_code(tueyecache.getTopicCode());
		String topid = UUIDGenerator.getUUID();
		topic.setId(topid); 
		
		topicService.saveTopics(topic);
	  //====================================================
		UserCollectionInfo collect = new UserCollectionInfo();
		collect.setSys_time(DateUtils.getCurrentDate());
		collect.setTopics(topic);
		collect.setUser(user);
		collect.setUserTopicType(1);
		collect.setId(UUIDGenerator.getUUID());
		topicService.saveTopicCollect(collect);
		
	 //===========================================================
		if(topicChange == 2){
			model.addAttribute("title", "<font color='red'>"+topic_title+"</font>近期推荐发布成功，请尽快填充其内容");
			viewName = "pages/topics/publishtopic/publishsuccess";
		}else{
			model.addAttribute("id", topid);
			viewName = "pages/topics/publishtopic/uploadpictures";
		}
		 
        return viewName;   
    } 
	
	 
}
